<!DOCTYPE HTML>
<html lang="en">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Vue-Router原理的深入探索, Casey Lu&#39;s Blog">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>Vue-Router原理的深入探索 | Casey Lu&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/medias/maozhao.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 4.2.0"><link rel="alternate" href="/atom.xml" title="Casey Lu's Blog" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Casey Lu's Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>Index</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>Tags</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>Categories</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>Archives</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>About</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="Search" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Casey Lu's Blog</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			Index
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			Tags
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			Categories
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			Archives
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			About
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('嘻嘻嘻，访问本文章需要密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误哦~');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/articleimages/21.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Vue-Router原理的深入探索</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Vue/">
                                <span class="chip bg-color">Vue</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/" class="post-category">
                                技术分享
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>Publish Date:&nbsp;&nbsp;
                    2020-04-16
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>Word Count:&nbsp;&nbsp;
                    2.6k
                </div>
                

                

                
            </div>

        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>之前Vue-Router对于我而言是非常好用的Vue的路由管理工具，多用于单页面应用中，但对于其底层的原理以及如何自己实现类似的管理工具没有太多的思考<img class="emoji" draggable="false" alt="💭" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f4ad.png"/>，最近深度读了下Router的源码，更好地理解它的内部实现逻辑和底层原理。</p>
<h2 id="Vue-Router的使用">Vue-Router的使用</h2>
<p>简单回忆下使用Router的步骤</p>
<ol>
<li><strong>安装包：</strong>  <code>npm i vue-router -S</code></li>
<li><strong>声明引入：</strong> 在main.js中引入，<code>import VueRouter from 'vue-router'</code></li>
<li><strong>安装插件：</strong> <code>Vue.use(VueRouter)</code></li>
<li><strong>创建及配置：</strong> 创建路由对象并且配置路由规则<br>
<code>let router = new VueRouter({toutes: [{path: '/home', component: Home}]})</code></li>
<li><strong>传递实例：</strong> 将路由对象传递给Vue实例 <code>router: router</code></li>
<li><strong>文件留坑：</strong> 在App.vue文件中留坑 <code>&lt;router-view&gt;&lt;/router-view&gt;</code></li>
</ol>
<p>除了基本使用还有动态路由匹配、嵌套路由和编程式导航以及重定向等多种使用详情，可以查看<a href="https://router.vuejs.org/zh/" target="_blank" rel="noopener">Vue-Router | 官方文档</a></p>
<h2 id="单页面SPA和多页面MPA">单页面SPA和多页面MPA</h2>
<p>在深度研究Vue-Router之前，先分析下单页面应用的特点，对单、多页面应用还不太了解的可以移步 《<a href="https://juejin.im/post/5a0ea4ec6fb9a0450407725c" target="_blank" rel="noopener">前端：你要懂的单页面和多页面</a>》这篇文章，但原文有点小问题。总结大概就是：</p>
<ul>
<li><strong>SPA</strong>—— 单个页面应用程序，仅有一张web页面；页面跳转仅刷新局部资源，公共资源仅需加载一次；应用于<strong>APP或客户端</strong></li>
<li><strong>MPA</strong>—— 多页面跳转刷新所有资源，每个资源选择性重复加载；常用于<strong>PC端官网、购物电商网站</strong>等</li>
</ul>
<p><img src="https://img-blog.csdnimg.cn/2020041617040671.png" alt="SPA vs. MPA "></p>
<p>综上所述<img class="emoji" draggable="false" alt="☝️" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/261d.png"/>，可以发现SPA的特点就是单个页面应用程序，加载页面的时候，不全部加载，只更新一个指定容器的内容。因此，SPA的核心之一是——更新视图不重新请求页面</p>
<h2 id="Vue-Router实现原理">Vue-Router实现原理</h2>
<p><img class="emoji" draggable="false" alt="⭐️" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/2b50.png"/> Vue-Router的原理核心是：<strong>更新视图不重新请求页面</strong><br>
Vue-Router在实现单页前端路由时，提供了一种方式：<strong>Hash模式，History模式，Abstract模式</strong>，根据模式参数决定采用哪种方式</p>
<p><strong>Router运行模式:</strong></p>
<ul>
<li>hash： 使用URL哈希值来作路由</li>
<li>history： 依赖HTML5历史记录API和服务器配置。查看HTML5历史记录模式。</li>
<li>abstract：支持所有Javascript运行环境，如Node.js服务端。</li>
</ul>
<p>VueRouter的构造方法(<code>src/index.js</code>)：</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">import { HashHistory } from './history/hash'
import { HTML5History } from './history/html5'
import { AbstractHistory } from './history/abstract'

    // ... more

    constructor(options: RouterOptions = {}) {
        // ... more

        // 默认hash模式
        let mode = options.mode || 'hash'

        // 是否降级处理
        this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false

        // 进行降级处理
        if (this.fallback) {
            mode = 'hash'
        }

        if (!inBrowser) {
            mode = 'abstract'
        }
        this.mode = mode

        // 根据不同的mode进行不同的处理
        switch (mode) {
            case 'history':
                this.history = new HTML5History(this, options.base)
                break
            case 'hash':
                this.history = new HashHistory(this, options.base, this.fallback)
                break
            case 'abstract':
                this.history = new AbstractHistory(this, options.base)
                break
            default:
                if (process.env.NODE_ENV !== 'production') {
                    assert(false, `invalid mode: ${mode}`)
                }
        }
    }
</code></pre>
<p>可以看出，根据mode确定类型，首先会判断是否支持<code>history</code>，然后根据 <code>fallback</code> 来确定是否要降级。然后，根据不同的 mode，分别实例化不同的 history 。 （<code>HTML5History</code>、<code>HashHistory</code>、<code>AbstractHistory</code>）</p>
<h2 id="（一）Hash模式">（一）Hash模式</h2>
<p>默认的模式，<strong>浏览器url中#后面的内容，包含#。</strong><br>
hash是URL中的锚点，代表的是网页中的一个位置，单单改变#后的部分，浏览器只会加载相应位置的内容，不会重新加载页面。</p>
<ul>
<li>#是用来指导浏览器动作的，对服务器端完全无用，HTTP请求中，不包含#。</li>
<li>每一次改变#后的部分，都会在浏览器的访问历史中增加一个记录，使用”后退”按钮，就可以返回上一个位置。</li>
</ul>
<p><strong>原理：</strong> Hash模式通过锚点值的改变，根据不同的值，渲染指定DOM位置的不同数据。</p>
<h2 id="（二）History模式">（二）History模式</h2>
<p>HTML5 History API提供了一种功能，能让开发人员在不刷新整个页面的情况下修改站点的URL，就是利用 <code>history.pushState</code> API 来完成 URL 跳转而无须重新加载页面。在不支持<code>history.pushState</code>的浏览器，会自动回退到hash模式。</p>
<blockquote>
<p>由于hash模式会在url中自带#，如果不想要很丑的 hash，我们可以用路由的 history模式，只需要在配置路由规则时，加入<code>&quot;mode: 'history'&quot;</code>，充分利用上面的<code>history.pushState</code> API，不需要重新加载页面<br>
是否回退到hash模式可以通过<code>fallback</code>配置项来控制，默认值是<code>true</code></p>
</blockquote>
<pre class=" language-language-javascript"><code class="language-language-javascript">// main.js
const router = new VueRouter({
  mode: 'history',
  routes: [...]
})
</code></pre>
<p><img class="emoji" draggable="false" alt="❓" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/2753.png"/> 有时，history模式下也会出现问题：</p>
<ul>
<li>hash模式下：<code>baidu.com/#/id=5</code> 请求地址为 <code>baidu.com</code>， 没有问题</li>
<li>history模式下：<code>baidu.com/id=5</code> 请求地址为 <code>baidu.com/id=5</code>，如果后端没有对应的路由处理，就会返回404错误<img class="emoji" draggable="false" alt="⚠️" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/26a0.png"/></li>
</ul>
<p><strong>解决：</strong> 为了应对这种情况，需要后台配置支持——在服务端增加一个覆盖所有情况的候选资源：如果 URL 匹配不到任何静态资源，则应该返回同一个 index.html 页面，这个页面就是我们app 依赖的页面。</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">export const routes = [
  {path: "/", name: "homeLink", component:Home}
  {path: "/register", name: "registerLink", component: Register},
  {path: "/login", name: "loginLink", component: Login},
  {path: "*", redirect: "/"}
]
</code></pre>
<p><em>此处就设置任意匹配，如果URL输入错误或者是URL匹配不到任何静态资源，就自动跳到到首页。</em></p>
<p><img src="https://img-blog.csdnimg.cn/20200416195738209.png" alt="history的目录"></p>
<p><img src="https://img-blog.csdnimg.cn/20200416195854963.png" alt="History类的基本关系图"><br>
History类的定义位于<code>base.js</code>，其中还定义了一系列方法，<code>hash</code>、<code>html5</code>模式分别继承了这些方法，并实现了自己特有的逻辑。从外部调用的时候，会直接调用到 <code>this.history</code> , 然后，由于初始化对象的不同，而进行不同的操作。</p>
<h2 id="（三）Abstract模式">（三）Abstract模式</h2>
<p><strong>abstract模式是使用一个不依赖于浏览器的浏览历史虚拟管理后端。</strong><br>
根据平台差异可以看出，在 Weex 环境中只支持使用 abstract 模式。 不过，vue-router 自身会对环境做校验，如果发现没有浏览器的 API，vue-router 会自动强制进入 abstract 模式，所以 在使用 vue-router 时只要不写 mode 配置即可，默认会在浏览器环境中使用 hash 模式，在移动端原生环境中使用 abstract 模式。<br>
当然，也可以明确指定在所有情况下都使用 abstract 模式。</p>
<h2 id="源码结构">源码结构</h2>
<p><img src="https://img-blog.csdnimg.cn/202004161939112.png" alt="Router的源码目录"><br>
其中，VueRouter对象，就在vue-router的入口文件<code>src/index.js</code>中<br>
VueRouter 原型上定义了一系列的函数，我们日常经常会使用到。主要有 ： <code>go</code> 、 <code>push</code> 、 <code>replace</code> 、 <code>back</code> 、 <code>forward</code> 。<br>
以及一些导航守护 ： <code>beforeEach</code> 、<code>beforeResolve</code> 、<code>afterEach</code> 等等<br>
上面html 中使用到的 router-view ，以及经常用到的 router-link 则存在 <code>src/components</code> 目录下。</p>
<h2 id="Vue开发插件的方式">Vue开发插件的方式</h2>
<p>Vue.js 要求插件应该有一个公开方法 install。这个方法的第一个参数是 Vue 构造器，第二个参数是一个可选的选项对象。<br>
在 install 方法里面，便可以做相关的处理：</p>
<ul>
<li>添加全局方法或者属性</li>
<li>添加全局资源：指令/过滤器/过渡等，</li>
<li>通过全局 <code>mixin</code> 方法添加一些组件选项，</li>
<li>添加 Vue 实例方法，通过把它们添加到 <code>Vue.prototype</code> 上实现。</li>
<li>一个库，提供自己的 API，同时提供上面提到的一个或多个功能</li>
</ul>
<p><strong>install的实现逻辑：</strong><br>
1） 防止重复安装<br>
2） 通过全局 <code>mixin</code> 注入一些生命周期的处理<br>
3） 挂载变量到原型上<br>
4） 注册全局组件</p>
<p><strong>install.js 的完整代码：</strong></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">import View from './components/view';
import Link from './components/link';

export let _Vue;

// 插件安装方法
export function install(Vue) {
    // 防止重复安装
    if (install.installed && _Vue === Vue) return;
    install.installed = true;

    _Vue = Vue;

    const isDef = v => v !== undefined;

    // 注册实例
    const registerInstance = (vm, callVal) => {
        let i = vm.$options._parentVnode;
        if (
            isDef(i) &&
            isDef((i = i.data)) &&
            isDef((i = i.registerRouteInstance))
        ) {
            i(vm, callVal);
        }
    };

    // 混入生命周期的一些处理
    Vue.mixin({
        beforeCreate() {
            if (isDef(this.$options.router)) {
                // 如果 router 已经定义了，则调用
                this._routerRoot = this;
                this._router = this.$options.router;
                this._router.init(this);
                Vue.util.defineReactive(
                    this,
                    '_route',
                    this._router.history.current
                );
            } else {
                this._routerRoot =
                    (this.$parent && this.$parent._routerRoot) || this;
            }
            // 注册实例
            registerInstance(this, this);
        },
        destroyed() {
            registerInstance(this);
        }
    });

    // 挂载变量到原型上
    Object.defineProperty(Vue.prototype, '$router', {
        get() {
            return this._routerRoot._router;
        }
    });

    // 挂载变量到原型上
    Object.defineProperty(Vue.prototype, '$route', {
        get() {
            return this._routerRoot._route;
        }
    });

    // 注册全局组件
    Vue.component('RouterView', View);
    Vue.component('RouterLink', Link);

    // 定义合并的策略
    const strats = Vue.config.optionMergeStrategies;
    // use the same hook merging strategy for route hooks
    strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate =
        strats.created;
}
</code></pre>
<h2 id="push方法解读">push方法解读</h2>
<p>在进行路由跳转的时候，通常都是使用<code>this.$router.push(...)</code>的形式进行调用</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">export default class VueRouter {
    // ... more

    push(location: RawLocation, onComplete?: Function, onAbort?: Function) {
        this.history.push(location, onComplete, onAbort);
    }
}
</code></pre>
<p>在<code>src/index.js</code>中的VueRouter对象上有一个push方法，但是直接转发到了<code>this.history.push(location, onComplete, onAbort)</code>，引起前面提到了，根据history初始化对象不同做不同的处理。</p>
<p>hash模式下：（<code>mode  === hash</code>）</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">export class HashHistory extends History {
    // ...more

    // 跳转到
    push(location: RawLocation, onComplete?: Function, onAbort?: Function) {
        const { current: fromRoute } = this;
        this.transitionTo(
            location,
            route => {
                pushHash(route.fullPath);
                handleScroll(this.router, route, fromRoute, false);
                onComplete && onComplete(route);
            },
            onAbort
        );
    }
}

// 切换路由
// 会判断是否支持pushState ，支持则使用pushState，否则切换hash
function pushHash(path) {
    if (supportsPushState) {
        pushState(getUrl(path));
    } else {
        window.location.hash = path;
    }
}
</code></pre>
<p>history模式下：（<code>mode  === history</code>）</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">export class HTML5History extends History {
    // ...more

    // 增加 hash
    push(location: RawLocation, onComplete?: Function, onAbort?: Function) {
        const { current: fromRoute } = this;
        this.transitionTo(
            location,
            route => {
                pushState(cleanPath(this.base + route.fullPath));
                handleScroll(this.router, route, fromRoute, false);
                onComplete && onComplete(route);
            },
            onAbort
        );
    }
}
</code></pre>
<p>都调用了<code>trasitionTo</code>，两种模式下push的区别在于：一个调用 <code>pushHash</code> ， 一个调用 <code>pushState</code>，而其他的 <code>go</code> 、 <code>replace</code> 、<code>getCurrentLocation</code> 都是类似的实现方式。</p>
<h2 id="路由匹配">路由匹配</h2>
<p>在进行路由跳转的时候，通常有以下四种方式：</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">// 字符串
router.push('home');
// 对象
router.push({ path: 'home' });
// 命名的路由
router.push({ name: 'user', params: { userId: '123' } });
// 带查询参数，变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' } });
</code></pre>
<p>但是push的具体对象与routes之间如何进行匹配，就涉及到了路由匹配的问题。</p>
<p><strong>路由匹配的具体步骤主要有：</strong></p>
<p>1） 实例化的时候，创建匹配器 ，并生成路由的映射关系 。匹配器中包含 <code>match</code> 方法<br>
2） <code>push</code> 的时候，调用到 <code>match</code> 方法<br>
3） <code>match</code> 方法里面，从路由的映射关系里面，通过编译好的正则来判定是否匹配，返回最终匹配的路由对象<br>
4） <code>transitionTo</code> 中，拿到匹配的路由对象，进行路由跳转</p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        Author:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://caseylu.gitee.io" rel="external nofollow noreferrer">Casey Lu</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        Link:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://caseylu.gitee.io/2020/04/16/29-vuerouter-yuan-li-de-shen-ru-tan-suo/">https://caseylu.gitee.io/2020/04/16/29-vuerouter-yuan-li-de-shen-ru-tan-suo/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        Reprint policy:
                    </i>
                </span>
                <span class="reprint-info">
                    All articles in this blog are used except for special statements
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    reprint polocy. If reproduced, please indicate source
                    <a href="https://caseylu.gitee.io" target="_blank">Casey Lu</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>Copied successfully, please follow the reprint policy of this article</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">more</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Vue/">
                                    <span class="chip bg-color">Vue</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">谢谢大佬的小鱼干，喵~</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'b739596984975414aa79',
        clientSecret: 'c5792bc3376f951910111f232176fbadfa919286',
        repo: 'L0ittle.github.io',
        owner: 'L0ittle',
        admin: "L0ittle",
        id: '2020-04-16T18-36-49',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;Previous</div>
            <div class="card">
                <a href="/2020/04/30/31-si-yue-tian-de-yi-zhi-xu-tao/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/articleimages/24.jpg" class="responsive-img" alt="四月天的一纸絮叨">
                        
                        <span class="card-title">四月天的一纸絮叨</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            这一个月的时间真心是飞速，回顾了三月底的flag，我觉得还算是满意的，至少没有让自己失望，感觉充实无比～吼吼吼
小有成长，空间辽阔
这个月算是一个过渡的月份，从学习状态到开发状态的切换，投身到真实的项目开发中，节奏比我想象中的要快，但是自己
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-04-30
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E4%BA%BA%E7%94%9F%E6%9D%82%E8%B0%88/" class="post-category">
                                    人生杂谈
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Life/">
                        <span class="chip bg-color">Life</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                Next&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/04/15/28-guan-yu-qian-duan-fan-pa-chong-ce-lue-de-tan-jiu/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/articleimages/18.jpg" class="responsive-img" alt="常见反爬虫策略的探究">
                        
                        <span class="card-title">常见反爬虫策略的探究</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            上周末百度三面面试官问的一个我最感兴趣的问题莫过于“对于淘宝京东之类的电商网站，防止商品价格被爬取，你会有哪些设计思路 ”在此之前，cc只是会通过代理IP手段来绕过一些反爬虫设置进行网站爬虫，但是没有思考过这样具体的应用场景。这篇Blog将
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-04-15
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/" class="post-category">
                                    技术分享
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%88%AC%E8%99%AB/">
                        <span class="chip bg-color">爬虫</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('100')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + 'From: Casey Lu&#39;s Blog<br />'
            + 'Author: Casey Lu<br />'
            + 'Link: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;TOC</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="4892766072"
                   fixed='true'
                   autoplay='false'
                   theme:='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2020</span>
            <a href="https://caseylu.gitee.io" target="_blank">Casey Lu</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">63.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/L0ittle" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:caseylu119@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1351238945" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1351238945" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;Search</span>
            <input type="search" id="searchInput" name="s" placeholder="Please enter a search keyword"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
